<template>
  <!-- 分配权限对话框组件 -->
  <el-dialog
    title="分配权限"
    :visible="dialogVisible"
    width="30%"
    :before-close="handleClose"
    top="2vh"
  >
    <!-- 对话框的树形结构区域 -->
    <el-tree
      show-checkbox
      :data="data"
      node-key="id"
      :props="defaultProps"
      default-expand-all
      :default-checked-keys="idArr"
      ref="treeRef"
    ></el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="defineRigiht"> 确 定 </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { request } from "@/utils/axios.js";

export default {
  components: {},
  props: ["dialogVisible"],
  data() {
    return {
      data: [],
      // 为树形结构指定绑定的字段
      defaultProps: {
        children: "children",
        label: "authName",
      },
      idArr: [],
      currentId: 0,
    };
  },
  watch: {},
  computed: {},
  methods: {
    handleClose() {
      // 清空列表元素
      this.idArr.length = 0;
      this.$emit("handleCloseDialog");
    },
    // 分配权限按钮
    async allotRights(rowData) {
      this.currentId = rowData.id;
      rowData = rowData.children;
      // 获取三级权限的id
      rowData.forEach((item) => {
        item.children.forEach((element) => {
          element.children.forEach((ele) => {
            this.idArr.push(ele.id);
          });
        });
      });
      const { data: ret } = await request.get(`rights/tree`);
      this.data = ret.data;
    },
    // 确定按钮方法定义
    async defineRigiht() {
      // 关闭对话框
      this.$emit("handleCloseDialog");
      const rids = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = rids.join(",");
      // 发起请求对权限进行分配
      await request.post(`roles/${this.currentId}/rights`, {
        rids: idStr,
      });
      this.$parent.getData();
    },
  },
  created() {},
  mounted() {},
};
</script>
<style lang="less" scoped>
</style>